<template>
  <div>
    <el-dialog :visible="visible" v-bind="$attrs" :title="form.id ?'编辑部门' :'新增部门'" v-on="$listeners" @open="onOpen" @close="onClose">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入部门编码" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择部门负责人" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in managerOptions"
              :key="index"
              :label="item.username"
              :value="item.username"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="form.introduce"
            type="textarea"
            placeholder="请输入部门介绍"
            :autosize="{minRows: 4, maxRows: 4}"
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeeSimple } from '@/api/Employees.js'
import { addDeptsAPI, editDeptsByIdAPI, getDeptsListAPI } from '@/api/departments'
export default {
  components: {},
  inheritAttrs: false,
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    node: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkName = async(rule, value, callback) => {
      let brother
      if (this.form.id) {
        // 编辑
        const allDepts = (await getDeptsListAPI().depts)
        brother = allDepts.filter(t => t.pid === this.form.pid && t.id !== this.form.id)
      } else {
        // 新增
        brother = this.node.children || []// 如果没有子节点
      }

      const f = brother.find(t => t.name === value)
      if (!f) {
        callback()
      } else {
        callback(new Error('存在重复名称的兄弟部门'))
      }
    }
    const checkCode = async(rule, value, callback) => {
      const allDepts = (await getDeptsListAPI()).depts
      let f
      if (this.form.id) {
        f = allDepts.filter(t => t.id !== this.form.id).find(t => // 注意{}如果不省略，return不能省略，否则找不到
          t.code === value

        )
      } else {
        f.allDepts.find(t => t.code === value)
      }

      if (!f) {
        callback()
      } else {
        callback(new Error('存在重复编码的部门'))
      }
    }
    return {
      form: {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      },
      rules: {
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        },
        { min: 1, max: 50, message: '请输入1到50个字符', trigger: 'blur' },
        { validator: checkName, trigger: 'blur' }],
        code: [{
          required: true,
          message: '请输入部门编码',
          trigger: 'blur'
        },
        { min: 1, max: 50, message: '请输入1到50个字符', trigger: 'blur' },
        { validator: checkCode, trigger: 'blur' }],
        manager: [{
          required: true,
          message: '请选择部门负责人',
          trigger: 'change'
        }],
        introduce: [{
          required: true,
          message: '请输入部门介绍',
          trigger: 'blur'
        }, { min: 1, max: 300, message: '请输入1到300个字符', trigger: 'blur' }]
      },
      managerOptions: []
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.managerOptions = await getEmployeeSimple()
  },
  mounted() {},
  methods: {
    onOpen() {},
    onClose() {
      // resetFields() 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      // 理解:
      // 初始值-最开始打开对话框之前form的值
      // 所有字段值-部分字段,在el-from-item有prop字段才可以
      // 所以只能手动清空

      this.$refs['formRef'].resetFields()
      this.form = {
        name: undefined,
        code: undefined,
        manager: undefined,
        introduce: undefined
      }
    },
    close() {
      this.$emit('update:visible', false)
    },
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => {
        if (!valid) return
        // 发请求
        // 判断是哪种情况，在发哪种请求，调用哪个接口
        if (this.form.id) { // 有id,调用编辑部门接口
          await editDeptsByIdAPI(this.form)
        } else { // 悟id调用添加部门接口
          await addDeptsAPI({
            ...this.form,
            pid: this.node.id
          })
        }

        // 提示一下
        this.$message.success('操作成功')
        // 刷新列表
        this.$emit('success')
        this.close()
      })
    }
  }
}

</script>
<style>
</style>
